package com.zhukaiyuan.oauth2.server.service.impl;

import com.zhukaiyuan.oauth2.sys.entity.Permission;
import com.zhukaiyuan.oauth2.sys.entity.User;
import com.zhukaiyuan.oauth2.sys.service.PermissionService;
import com.zhukaiyuan.oauth2.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);
        if (user!=null){
            List<Permission> permissions = permissionService.getByUserId(user.getId());
            ArrayList<GrantedAuthority> arrayList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(permissions)){
                permissions.forEach(p -> {
                    GrantedAuthority authority = new SimpleGrantedAuthority(p.getEnname());
                    arrayList.add(authority);
                });
            }
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(), arrayList);
        }
        return null;
    }
}
